<template>
	<div class="layout-padding">
		<div class="fenxi">
			<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
				<el-tab-pane label="部门" name="departmentId"></el-tab-pane>
				<el-tab-pane label="区域" name="areaId"></el-tab-pane>
				<el-tab-pane label="分项" name="modelType"></el-tab-pane>
				<el-tab-pane label="支路" name="branchingId"></el-tab-pane>
				<el-tab-pane label="设备" name="equipment"></el-tab-pane>
			</el-tabs>
			<div class="content">
				<div class="level">
					<div class="level-l">
						<div class="head" v-if="activeName != 'modelType' && activeName != 'branchingId'">能耗分类</div>
						<div class="shui-dian" v-if="activeName != 'modelType' && activeName != 'branchingId'">
							<span v-for="(item, index) in sortData" :key="index" :class="[sdIndex == item.value ? 'active' : '']" @click="queryData(item)">{{
								item.label
							}}</span>
						</div>

						<div class="head">统计对象</div>
						<div :class="[activeName !== 'modelType' && activeName !== 'branchingId' ? 'dept2' : 'dept']">
							<el-scrollbar class="data-scrollbar">
								<el-input placeholder="输入关键字进行过滤" v-model="deptName" style="margin-bottom: 10px"> </el-input>
								<el-tree
									ref="deptTree"
									default-expand-all
									multiple
									checkStrictly
									show-checkbox
									node-key="id"
									placeholder="请选择 上级部门"
									:data="treeData"
									:props="treeDataProps"
									:current-node-key="currentNodeKey"
									:expand-on-click-node="false"
									:filter-node-method="filterNode"
								></el-tree>
							</el-scrollbar>
						</div>
					</div>

					<div class="level-r">
						<el-scrollbar class="data-scrollbar">
							<div class="condition">
								<div class="time">
									<div class="select-con">
										<div>统计周期:</div>

										<el-select v-model="dateType2" placeholder="请选择" @change="dateTypeChange2">
											<el-option label="时" value="datetimerange"></el-option>
											<el-option label="日" value="daterange"></el-option>
											<el-option label="月" value="monthrange"></el-option>
											<el-option label="年" value="yearrange"></el-option>
										</el-select>
									</div>
									<div class="time-picker">
										<div>
											<el-date-picker
												style="width: 350px"
												v-model="value2"
												:type="dateType2"
												placeholder="请选择"
												:format="dateFormat2"
												:value-format="dateFormat2"
												:disabled-date="pickerOptions1"
											/>
										</div>
									</div>
									<el-button style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">查询 </el-button>
									<el-button style="margin-left: 10px" class="filter-item" icon="el-icon-refresh" @click="resetSearch">重置 </el-button>
								</div>
							</div>

							<div class="level-content">
								<span class="unit">{{ alleywayUnit }}</span>
								<div id="data-chart" ref="dataChart"></div>
								<avue-crud ref="crud" v-model="form" :data="tableData" :table-loading="tableLoading" :option="tableOption"></avue-crud>
							</div>
						</el-scrollbar>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import echarts from '/@/utils/chart';
import { getDateByType } from '/@/utils/util';
import { getPowerSubitem, deptConfigData, deptCompareByChart } from '/@/api/consumptionmanagement/energyanalysis/compare';
import moment from 'moment';

let myChart;
export default {
	components: {},
	data() {
		return {
			activeName: 'areaId',
			dateType2: 'datetimerange',
			sdIndex: 1,
			value2: [],
			treeData: [],
			treeDataProps: {
				label: 'name',
				value: 'id',
			},
			dateFormat2: 'YYYY-MM-DD HH',
			alleywayUnit: 'kw.h',
			sortData: [],
			itemData: [],
			tableData: [],
			defaultColumn: [
				{
					type: 'input',
					label: '汇总项',
					prop: 'reportName',
					fixed: 'left',
					width: 180,
					overHidden: true,
				},
				{
					type: 'input',
					label: '总和',
					prop: 'sumTotal',
					fixed: 'left',
					width: 180,
					overHidden: true,
				},
			],
			tableOption: {
				border: true,
				excelBtn: true,
				gridBtn: false,
				index: true,
				indexLabel: '序号',
				stripe: true,
				labelWidth: '160',
				indexWidth: '60',
				menuAlign: 'center',
				align: 'center',
				addBtn: false,
				menu: false,
				maxHeight: 600,
				fit: true,
				refreshBtn: false,
				columnBtn: false,
				searchMenuSpan: 6,
				searchLabelWidth: 'auto',
				searchMenuPosition: 'left',
				column: [
					{
						type: 'input',
						label: '汇总项',
						prop: 'reportName',
						fixed: 'left',
						width: 180,
						overHidden: true,
					},
					{
						type: 'input',
						label: '总和',
						prop: 'sumTotal',
						fixed: 'left',
						width: 180,
						overHidden: true,
					},
				],
			},
			form: {},
			energyType: '1',
			fileKey: 'areaId',
			// fileValue: '1635540877329244201',
			fileValue: '',
			highlight: true,
			growthRate: '',
			fenxiangIndex: 1,
			deptName: '',
			currentNodeKey: '',
			deptUnitNo: '',
			dimTypeObj: {
				areaId: 'powerAreaContrast',
				departmentId: 'powerDeptContrast',
				equipment: 'powerKeqContrast',
				branchingId: 'powerBranchContrast',
				modelType: 'powerSubitemContrast',
			},
		};
	},
	watch: {
		deptName(val) {
			this.$refs.deptTree.filter(val);
		},
		dateType2: {
			handler(val, oldVal) {
				if (val == 'yearrange') {
					this.dateFormat2 = 'YYYY';
				} else if (val == 'monthrange') {
					this.dateFormat2 = 'YYYY-MM';
				} else if (val == 'datetimerange') {
					this.dateFormat2 = 'YYYY-MM-DD HH';
				} else {
					this.dateFormat2 = 'YYYY-MM-DD';
				}
			},
			immediate: true,
		},
	},
	created() {
		// let dateObj = this.getNowDate();
		// this.value2 = [dateObj.date, dateObj.date];
		getPowerSubitem().then((res) => {
			this.sortData = res.data;
		});
	},
	mounted() {
		this.value2 = [moment().startOf('day').hour(1).format('YYYY-MM-DD HH'), moment().format('YYYY-MM-DD HH')];
		this.getDeptConfigData(1);
		setTimeout(() => {
			this.searchData();
		}, 1000);
	},
	methods: {
		pickerOptions1(time) {
			return time.getTime() > Date.now();
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.label.indexOf(value) !== -1;
		},
		getDeptConfigData(type) {
			let str;
			if (this.fileKey == 'departmentId') {
				str = 'dimdept';
			} else if (this.fileKey == 'areaId') {
				str = 'dimarea';
			} else if (this.fileKey == 'modelType') {
				str = 'dimSubitem';
			} else if (this.fileKey == 'branchingId') {
				str = 'dimBranch';
			} else if (this.fileKey == 'equipment') {
				str = 'dimKeq';
			}
			deptConfigData(type, str).then((res) => {
				this.treeData = res.data;

				if (!this.validatenull(this.treeData)) {
					this.currentNodeKey = this.treeData[0].id;

					this.$nextTick(() => {
						this.$refs.deptTree.setCurrentKey(this.currentNodeKey);
						this.$refs.deptTree.setCheckedKeys([this.currentNodeKey]);
					});
				}
			});
		},
		// exportExcel() {
		// 	this.$store.commit('openIframe', [
		// 		true,
		// 		`/report/jmreport/view/f5f275b5e28b45256ef24587ec792f0c?token＝${this.access_token}&date=${this.value2}&energyType=${this.energyType}&fileKey=${this.fileKey}&fileValue=${this.fileValue}&compareType=${this.compareType}`,
		// 	]);
		// },
		closeIframe() {
			this.$store.commit('openIframe', [false, '']);
		},
		handleClick(tab, event) {
			this.setQuery();
			this.fileKey = tab.props.name;
			if (this.fileKey == 'departmentId') {
				this.getDeptConfigData(1);
			} else if (this.fileKey == 'areaId') {
				this.getDeptConfigData(1);
			} else if (this.fileKey == 'modelType') {
				this.getDeptConfigData();
			} else if (this.fileKey == 'branchingId') {
				this.getDeptConfigData();
			} else if (this.fileKey == 'equipment') {
				this.getDeptConfigData(1);
			}
			this.resetChart();
		},
		initChart(xData, legendData, seriesData) {
			//检测是否已经存在echarts实例，如果不存在，则不再去初始化
			myChart = echarts.getInstanceByDom(this.$refs.dataChart);

			const series = legendData.map((name, sid) => {
				return {
					name,
					type: 'line',
					smooth: true,
					data: seriesData.filter((obj) => {
						return obj.name == name;
					})[0].data,
					markPoint: {
						data: [
							{ type: 'max', name: 'Max' },
							{ type: 'min', name: 'Min' },
						],
					},
				};
			});
			//如果为空 则正常进行渲染 反之 不再进行初始化
			if (myChart == null) {
				myChart = echarts.init(this.$refs.dataChart);
			} else {
				myChart.clear();
			}
			myChart.setOption({
				grid: {
					left: 50,
					top: 80,
					bottom: 30,
					right: 10,
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'cross',
					},
					textStyle: {
						color: '#333',
						fontSize: 14,
					},
				},
				toolbox: {
					show: true,
					feature: {
						magicType: { type: ['line', 'bar'] },
						restore: {},
						saveAsImage: {},
					},
				},
				legend: {
					show: true,
					top: '3%',
				},
				xAxis: {
					type: 'category',
					data: xData,
					axisLabel: {
						show: true,
						color: '#999',
					},
					axisLine: {
						show: true,
						lineStyle: {
							color: '#0ba2b6',
						},
					},
				},
				yAxis: {
					type: 'value',
					axisLabel: {
						color: '#999',
					},
					axisLine: {
						show: true,
						lineStyle: {
							color: '#0ba2b6',
						},
					},
					splitLine: {
						lineStyle: {
							color: '#345787',
							type: 'dashed', // y轴分割线类型
						},
					},
				},
				series,
			});
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.name.includes(value);
		},
		// 切换统计周期，同比没有日周期和月周期
		dateTypeChange2(val) {
			this.dateType2 = val;
			if (val == 'yearrange') {
				this.value2 = [this.getNowDate().year, this.getNowDate().year];
			} else if (val == 'monthrange') {
				this.value2 = [this.getNowDate().month, this.getNowDate().month];
			} else if (this.dateType2 == 'datetimerange') {
				this.value2 = [moment().startOf('day').hour(1).format('YYYY-MM-DD HH'), moment().format('YYYY-MM-DD HH')];
			} else {
				this.value2 = [this.getNowDate().date, this.getNowDate().date];
			}
		},
		// changeDate2(val) {
		// 	this.value2 = val;
		// },
		queryData(item) {
			this.sdIndex = item.value;
			if (item.value == 1) {
				this.alleywayUnit = 'kwh';
			} else if (item.value == 2) {
				this.alleywayUnit = 't';
			} else if (item.value == 3) {
				this.alleywayUnit = 'm³';
			}
			this.getDeptConfigData(item.value);
			this.setQuery();
			this.resetChart();
		},
		searchData() {
			let depts = this.$refs.deptTree.getCheckedKeys();
			if (depts.length > 6) {
				this.$message.warning('统计对象最多可选择6个');
				return;
			}
			if (this.validatenull(this.value2)) {
				this.$message.warning('请选择日期');
				return;
			}

			let params = {
				ids: depts.join(','),
				energyType: this.sdIndex,
				// date: this.value2,
				startDate: this.value2[0],
				endDate: this.value2[1],
			};
			this.tableLoading = true;
			deptCompareByChart(params, this.dimTypeObj[this.activeName])
				.then((res) => {
					this.tableLoading = false;
					this.tableData = res.data.tableData || [];
					let xData = res.data.resultLayer.xAxisData;
					let legendData = res.data.resultLayer.legendData;
					let seriesData = res.data.resultLayer.series;
					this.initChart(xData, legendData, seriesData);
					this.setTableColumn(this.dateType2, xData);
				})
				.catch((err) => {
					this.tableLoading = false;
				});
		},
		//重置
		resetSearch() {
			this.$refs.deptTree.setCheckedKeys([]);
			if (this.dateType2 == 'yearrange') {
				this.value2 = [this.getNowDate().year, this.getNowDate().year];
			} else if (this.dateType2 == 'monthrange') {
				this.value2 = [this.getNowDate().month, this.getNowDate().month];
			} else if (this.dateType2 == 'datetimerange') {
				this.value2 = [moment().startOf('day').hour(1).format('YYYY-MM-DD HH'), moment().format('YYYY-MM-DD HH')];
			} else {
				this.value2 = [this.getNowDate().date, this.getNowDate().date];
			}
		},
		setTableColumn(type, columnData) {
			let column = [];
			let dataColumn = this.getFormatColumn(type, columnData);
			this.tableOption.column = [];
			this.tableOption.column = [...this.defaultColumn, ...dataColumn];
		},
		getFormatColumn(type, columnData) {
			let list = [];
			if (type == 'daterange') {
				if (this.value2[0] == this.value2[1]) {
					for (let i = 1; i <= 24; i++) {
						list.push({
							type: 'input',
							label: (i < 10 ? '0' + i : '' + i) + '时',
							prop: 'd_' + (i < 10 ? '0' + i : '' + i),
						});
					}
				} else {
					for (let i = 0; i < columnData.length; i++) {
						list.push({
							type: 'input',
							width: 100,
							label: columnData[i],
							prop: 'q_' + columnData[i],
						});
					}
				}
			} else if (type == 'monthrange') {
				if (this.value2[0] == this.value2[1]) {
					for (let i = 1; i <= 31; i++) {
						list.push({
							type: 'input',
							label: (i < 10 ? '0' + i : '' + i) + '日',
							prop: 'm_' + (i < 10 ? '0' + i : '' + i),
						});
					}
				} else {
					for (let i = 0; i < columnData.length; i++) {
						list.push({
							type: 'input',
							width: 100,
							label: columnData[i],
							prop: 'q_' + columnData[i],
						});
					}
				}
			} else if (type == 'yearrange') {
				if (this.value2[0] == this.value2[1]) {
					for (let i = 1; i <= 12; i++) {
						list.push({
							type: 'input',
							label: (i < 10 ? '0' + i : '' + i) + '月',
							prop: 'y_' + (i < 10 ? '0' + i : '' + i),
						});
					}
				} else {
					for (let i = 0; i < columnData.length; i++) {
						list.push({
							type: 'input',
							width: 100,
							label: columnData[i],
							prop: 'q_' + columnData[i],
						});
					}
				}
			} else if (type == 'datetimerange') {
				for (let i = 0; i < columnData.length; i++) {
					list.push({
						type: 'input',
						width: 100,
						label: columnData[i],
						prop: 'q_' + columnData[i],
					});
				}
			}
			return list;
		},
		setQuery() {
			this.dateType2 = 'datetimerange';
			this.dateFormat2 = 'YYYY-MM-DD HH';
			this.value2 = [moment().startOf('day').hour(1).format('YYYY-MM-DD HH'), moment().format('YYYY-MM-DD HH')];
			this.tableData = [];
		},
		resetChart() {
			// 清除当前图表的所有配置和数据
			myChart?.clear();
			//  myChart.restore()
		},
		getNowDate() {
			let dateObj = getDateByType();
			let obj = {
				year: '',
				month: '',
				date: '',
			};
			obj.year = String(dateObj.year);
			obj.month = dateObj.year + '-' + dateObj.month;
			obj.date = dateObj.year + '-' + dateObj.month + '-' + dateObj.date;
			return obj;
		},
	},
};
</script>

<style lang="scss" scoped>
#data-chart {
	height: 400px;
}
.data-scrollbar {
	.area-item {
		margin: 10px 30px;
		.active {
			background: var(--el-color-primary);
			color: #fff;
		}
		span {
			display: inline-block;
			width: 320px;
			height: 36px;
			line-height: 36px;
			border-radius: 4px;
			font-size: 15px;
			text-align: center;
			transition: all 0.5s;
			cursor: pointer;
			border: 1px solid #efefef;
			&:hover {
				background: var(--el-color-primary);
				color: #fff;
			}
		}
	}
}
.fenxi {
	height: 100%;
	::v-deep .demo-tabs {
		background: #fff;
		padding: 10px;
		.el-tabs__header {
			margin-bottom: 0;
			display: inline-block;
		}
		.el-tabs__nav-wrap:after {
			background-color: initial;
		}
		.el-tabs__item {
			// height: 60px;
			// line-height: 60px;
			margin: 0 10px;
		}
	}
	.content {
		margin-top: 10px;
		height: calc(100% - 73px);
	}
	.level {
		display: flex;
		height: 100%;
		.level-l {
			width: 20%;
			background: #fff;
			margin-right: 6px;
		}
		.level-r {
			width: 80%;
			margin-left: 6px;
		}
		.shui-dian {
			border-top: 1px solid #eee;
			padding: 20px;
			// text-align: center;
			.active {
				background: var(--el-color-primary);
				color: #fff;
			}
			span {
				display: inline-block;
				width: 80px;
				height: 36px;
				line-height: 36px;
				border-radius: 4px;
				color: #333;
				margin-right: 10px;
				margin-top: 10px;
				text-align: center;
				transition: all 0.5s;
				cursor: pointer;
				border: 1px solid #efefef;
				&:hover {
					background: var(--el-color-primary);
					color: #fff;
				}
			}
		}
		.condition {
			height: 64px;
			border: 1px solid #efefef;
			background: #fff;
			display: flex;
			align-items: center;
			padding: 0 10px;
		}
		.level-content {
			position: relative;
			background: #fff;
			margin-top: 10px;
			padding: 0 10px;
			width: 100%;
			height: calc(100% - 96px);
			.data-table {
				margin-top: 30px;
			}
			.unit {
				position: absolute;
				left: 20px;
				top: 10px;
				font-size: 14px;
				font-weight: 700;
			}
		}
	}
}
.head {
	padding: 20px 10px;
	position: relative;
	font-size: 18px;
	padding-left: 25px;
	&:before {
		content: '';
		width: 2px;
		position: absolute;
		height: 24px;
		left: 10px;
		background: var(--el-color-primary);
	}
}
.select-con {
	display: flex;
	align-items: center;
	.el-select {
		margin-left: 5px;
		width: 90px;
	}
}
.time {
	display: flex;
	align-items: center;
	.time-tab {
		display: flex;
		align-items: center;
		border: 1px solid #eee;
		border-radius: 4px;
		margin-right: 50px;
		div {
			// margin: 0 15px;
			padding: 0 20px;
			height: 36px;
			transition: all 0.5s;
			line-height: 36px;
			text-align: center;
			cursor: pointer;
			&:not(:last-child) {
				border-right: 1px solid #eee;
			}
			&:hover {
				background: var(--el-color-primary);
				color: #fff;
			}
		}
		.active {
			background: var(--el-color-primary);
			color: #fff;
		}
	}
}
.huanbi {
	margin-left: 50px;
}
.dept,
.dept2,
.area {
	padding: 0 10px;
	border-top: 1px solid #eee;
	padding-top: 10px;
}

.dept {
	height: calc(100% - 67px);
}
.dept2 {
	height: calc(100% - 67px - 87px - 67px);
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
	background: #eaeaea;
}
.time-picker {
	margin-left: 10px;
	width: 370px;
}
</style>
